<template>
  <el-form :model="activity" label-width="100px" class="activity-form">
    <el-form-item label="活动名称" required>
      <el-input v-model="activity.activityName" placeholder="请输入活动名称" />
    </el-form-item>

    <el-form-item label="活动举行时间" required>
      <el-date-picker
        v-model="activity.holdTime"
        type="date"
        format="YYYY 年 MM 月 DD 日"
        value-format="YYYY 年 MM 月 DD 日"
        placeholder="选择日期"
      />
    </el-form-item>

    <el-form-item label="活动地点" required>
      <el-input v-model="activity.site" placeholder="请输入活动地点" />
    </el-form-item>

    <el-form-item label="活动简介">
      <QuillEditor
        v-model:content="activity.introduce"
        :options="editorOption"
        theme="snow"
        toolbar="full"
        contentType="html"
        class="editor-container"
      />
    </el-form-item>

    <el-form-item label="活动图片">
      <el-upload
        ref="uploadRef"
        class="upload-demo"
        :action="uploadAction"
        :on-change="handleChange"
        :file-list="fileList"
        :on-remove="beforeRemove"
        :auto-upload="false"
        :limit="3"
      >
        <template #trigger>
          <el-button type="primary">
            <el-icon><Upload /></el-icon>
            选取图片
          </el-button>
        </template>
        <template #tip>
          <div class="el-upload__tip">选择要上传的图片，且不超过1M</div>
        </template>
      </el-upload>
    </el-form-item>

    <el-form-item label="活动类型" required>
      <el-select
        v-model="activity.activityTypeId"
        placeholder="请选择活动类型"
        class="activity-type-select"
      >
        <el-option
          v-for="activityType in activityTypeList"
          :key="activityType.id"
          :label="activityType.type"
          :value="activityType.id"
        />
      </el-select>
    </el-form-item>

    <el-form-item>
      <div class="button-group">
        <el-button type="primary" @click="handleSubmit">
          <el-icon><Plus /></el-icon>
          添加活动
        </el-button>
        <el-button @click="goBack">
          <el-icon><Back /></el-icon>
          返回
        </el-button>
      </div>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { QuillEditor } from "@vueup/vue-quill";
import "@vueup/vue-quill/dist/vue-quill.snow.css";
import { Plus, Upload, Back } from "@element-plus/icons-vue";
import axios from "axios";

const OK = 200;
const router = useRouter();
const uploadRef = ref(null);

// 响应式状态
const activity = reactive({
  activityName: "",
  holdTime: "",
  site: "",
  introduce: "",
  activityTypeId: "",
});

const activityTypeList = ref([]);
const fileList = ref([]);
const relativePath = ref("/images/activity/");
const uploadAction = computed(
  () => "/api/files/uploadImg?relativePath=" + relativePath.value
);
const editorOption = {
  placeholder: "请输入活动简介",
  theme: "snow",
  modules: {
    toolbar: [
      ["bold", "italic", "underline", "strike"],
      ["blockquote", "code-block"],
      [{ header: 1 }, { header: 2 }],
      [{ list: "ordered" }, { list: "bullet" }],
      [{ script: "sub" }, { script: "super" }],
      [{ indent: "-1" }, { indent: "+1" }],
      [{ direction: "rtl" }],
      [{ size: ["small", false, "large", "huge"] }],
      [{ header: [1, 2, 3, 4, 5, 6, false] }],
      [{ color: [] }, { background: [] }],
      [{ font: [] }],
      [{ align: [] }],
      ["clean"],
      ["link", "image"],
    ],
  },
};

// 文件对象
const file = reactive({
  activityId: 0,
  filePath: "",
  fileName: "",
});

// 提交表单
const handleSubmit = async () => {
  try {
    // 表单验证
    if (!activity.activityName?.trim()) {
      ElMessage.warning("请输入活动名称");
      return;
    }
    if (!activity.holdTime) {
      ElMessage.warning("请选择活动举行时间");
      return;
    }
    if (!activity.site?.trim()) {
      ElMessage.warning("请输入活动地点");
      return;
    }
    if (!activity.activityTypeId) {
      ElMessage.warning("请选择活动类型");
      return;
    }

    // 添加活动
    const res = await axios.post("/api/activities/", activity);
    if (res.data.code === OK) {
      file.activityId = res.data.data;

      // 如果有选择文件，则上传文件
      if (fileList.value.length > 0) {
        try {
          await uploadRef.value?.submit();
        } catch (error) {
          console.error("文件上传失败:", error);
          ElMessage.warning("文件上传失败，但活动已创建成功");
        }
      }

      ElMessage.success("添加活动成功");

      // 延迟跳转，等待文件上传完成
      setTimeout(() => {
        router.push({ name: "ActivityList" });
      }, 1500);
    } else {
      ElMessage.error(res.data.message || "添加活动失败");
    }
  } catch (error) {
    console.error("添加活动失败:", error);
    ElMessage.error("添加活动失败，请重试");
  }
};

// 获取活动类型列表
const getActivityTypeList = async () => {
  try {
    const res = await axios.get("/api/activityTypes");
    if (res.data.code === OK) {
      activityTypeList.value = res.data.data;
    } else {
      ElMessage.error(res.data.message || "获取活动类型失败");
    }
  } catch (error) {
    console.error("获取活动类型失败:", error);
    ElMessage.error("获取活动类型失败，请重试");
  }
};

// 处理文件变化
const handleChange = async (uploadFile, uploadFiles) => {
  const response = uploadFile.response;
  if (response?.code === OK) {
    file.filePath = response.data;
    file.fileName = getFileName(file.filePath);
    await saveFile();
    ElMessage.success("上传文件成功");
  }
  fileList.value = uploadFiles.slice(-3);
};

// 保存文件信息
const saveFile = async () => {
  if (!file.activityId || !file.filePath) return;

  try {
    const res = await axios.post("/api/files/activity", file);
    if (res.data.code !== OK) {
      ElMessage.error(res.data.message || "保存文件信息失败");
    }
  } catch (error) {
    console.error("保存文件信息失败:", error);
    ElMessage.error("保存文件信息失败，请重试");
  }
};

// 删除文件前确认
const beforeRemove = (uploadFile) => {
  return ElMessageBox.confirm("确定移除 " + uploadFile.name + "？");
};

// 获取文件名
const getFileName = (filePath) => {
  if (!filePath) return null;
  const lastSlashIndex = filePath.lastIndexOf("/");
  return lastSlashIndex !== -1 ? filePath.substring(lastSlashIndex + 1) : null;
};

// 返回上一页
const goBack = () => {
  ElMessageBox.confirm("确定要返回吗？未保存的内容将会丢失", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      router.back();
    })
    .catch(() => {});
};

// 页面加载时获取活动类型列表
onMounted(() => {
  getActivityTypeList();
});
</script>

<style scoped>
.activity-form {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.editor-container {
  width: 1024px !important;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.editor-container.ql-container.ql-snow {
  width: 100%;
  height: 40px;
}
.ql-toolbar.ql-snow + .ql-container.ql-snow {
  height: 40px;
  width: 100%;
  border-top: 0px;
}
.ql-toolbar.ql-snow + .ql-container.ql-snow {
  width: 100%;
  border-top: 0px;
  height: 40px;
}
:deep(.ql-container) {
  min-height: 200px;
}

.upload-demo {
  margin: 20px 0;
}

.el-upload__tip {
  margin-top: 8px;
  color: #666;
}

.button-group {
  display: flex;
  gap: 12px;
  justify-content: center;
  margin-top: 20px;
}

.activity-type-select {
  width: 100%;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-button .el-icon) {
  margin-right: 4px;
}

:deep(.ql-toolbar) {
  border-top-left-radius: 4px;
  border-top-right-radius: 4px;
}

:deep(.ql-container) {
  border-bottom-left-radius: 4px;
  border-bottom-right-radius: 4px;
}
</style>`
